package com.czwx.bee.business.manager.modular.sys.controller;

import cn.hutool.core.bean.BeanUtil;
import com.czwx.bee.base.common.dto.ResponseDto;
import com.czwx.bee.base.common.exception.BizExceptionEnum;
import com.czwx.bee.base.common.exception.BusinessException;
import com.czwx.bee.base.common.interfaces.BpUserStatusEnum;
import com.czwx.bee.base.common.interfaces.BpUserTypeEnum;
import com.czwx.bee.base.common.utils.MD5Util;
import com.czwx.bee.base.web.common.BaseController;
import com.czwx.bee.business.manager.exception.ManagerExceptionEnum;
import com.czwx.bee.business.manager.modular.sys.model.Role;
import com.czwx.bee.business.manager.modular.sys.model.SecurityUser;
import com.czwx.bee.business.manager.modular.sys.model.User;
import com.czwx.bee.business.manager.modular.sys.model.query.UserQuery;
import com.czwx.bee.business.manager.modular.sys.service.RoleService;
import com.czwx.bee.business.manager.modular.sys.service.UserService;
import com.czwx.bee.business.manager.utils.ManagerExceptionUtil;
import com.czwx.bee.business.manager.utils.SecurityUtil;
import io.swagger.annotations.*;
import org.beetl.sql.core.engine.PageQuery;
import org.hibernate.validator.constraints.Length;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.security.Security;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author:wiki
 * @Date:Create in 2018/7/3 0003 下午 4:13
 */

@Api(value = "UserController",tags = "用户控制器")
@RestController
@RequestMapping("user")
@Validated
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("auth_user")
    @ApiOperation(value = "用户授权角色", notes = "用户授权角色", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "请输入凭证", required = true, dataType = "String", paramType = "header"),
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "rids", value = "角色id字符串", required = true, dataType = "String", paramType = "query"),

    })
    public ResponseDto authUser(@NotNull(message = "用户id不能为空") Long userId,@NotNull(message = "角色id字符串不能为空") String rids){
        ResponseDto rs=new ResponseDto(BizExceptionEnum.SUCCESSFUL_OPERATION);
        SecurityUser securityUser=SecurityUtil.getSecurityUser();
        User user=userService.getById(userId);
        if(user==null){
              rs.ChangeBizException(BizExceptionEnum.NO_THIS_USER);
              return rs;
        }
        userService.authUser(userId,rids);
        return rs;
    }

    @PostMapping("modifyPwd")
    @ApiOperation(value = "修改用户密码", notes = "修改用户密码", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "请输入凭证", required = true, dataType = "String", paramType = "header"),
            @ApiImplicitParam(name = "newPwd", value = "新密码", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "oldPwd", value = "旧密码", required = true, dataType = "String", paramType = "query")
    })
    public ResponseDto modifyPwd(
            @NotEmpty(message = "新密码不能为空")
                    String newPwd,
            @NotEmpty(message = "旧密码不能为空") @Length(min = 6, message = "密码长度不能小于6位")
                    String oldPwd
    ) {
        ResponseDto rs = new ResponseDto(BizExceptionEnum.SUCCESSFUL_OPERATION);
        SecurityUser securityUser=SecurityUtil.getSecurityUser();
        if(!MD5Util.getMd5Value(oldPwd).equals(securityUser.getPassword())){
            throw new BusinessException(BizExceptionEnum.OLD_PWD_NOT_RIGHT);
        }
        User user=new User();
        user.setId(securityUser.getId());
        user.setPassword(newPwd);
        userService.update(user);
        return rs;
    }

    @PostMapping("resetPwd")
    @ApiOperation(value = "重置密码", notes = "重置密码", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "请输入凭证", required = true, dataType = "String", paramType = "header"),
            @ApiImplicitParam(name = "ids", value = "用户id字符串", required = true, dataType = "String", paramType = "query"),
    })
    public ResponseDto modifyPwd(@NotNull(message = "用户ids不能为空") String ids){
        ResponseDto rs = new ResponseDto(BizExceptionEnum.SUCCESSFUL_OPERATION);
        userService.resetPwd(ids);
        return rs;
    }

    @PostMapping("change_status")
    @ApiOperation(value = "锁定/解锁", notes = "type：0锁定 1解锁", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "请输入凭证", required = true, dataType = "String", paramType = "header"),
            @ApiImplicitParam(name = "ids", value = "用户id字符串", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "类型", required = true, dataType = "Integer", paramType = "query"),
    })
    public ResponseDto changeStatus(@NotNull(message = "用户ids不能为空") String ids,@NotNull(message = "tpye不能为空") Integer type){
        ResponseDto rs = new ResponseDto(BizExceptionEnum.SUCCESSFUL_OPERATION);
        userService.changeStatus(type,ids);
        return rs;
    }


    @PostMapping("list")
    @ApiOperation(value = "用户列表", notes = "用户列表", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "请输入凭证", required = true, dataType = "String", paramType = "header"),
            @ApiImplicitParam(name = "userQuery", value = "请输入用户查询信息", required = true, dataType = "UserQuery", paramType = "body") })
    @ApiResponses(
            @ApiResponse(code = 200,response = User.class,message = "data：中返回list")
    )
    public ResponseDto userList(@Validated @RequestBody UserQuery userQuery) throws Exception {
        ResponseDto rs=new ResponseDto(BizExceptionEnum.SUCCESSFUL_OPERATION);
        SecurityUser securityUser=new SecurityUser();
        Map map=BeanUtil.beanToMap(userQuery,false,true);
        if(securityUser.getUserType()== BpUserTypeEnum.SHOP_ADMIN.getCode()){
                map.put("drainage_id",securityUser.getDrainageId());
        }
        PageQuery<User> query=  new PageQuery(userQuery.getPage(),userQuery.getSize(),objectToMap(userQuery));
        userService.getPageList(query);
        rs.setData(query);
        return rs;
    }

    @PostMapping("save")
    @ApiOperation(value = "用户添加或修改", notes = "用户添加或修改", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "请输入凭证", required = true, dataType = "String", paramType = "header"),
            @ApiImplicitParam(name = "user", value = "请输入用户信息", required = true, dataType = "User", paramType = "body") })
    public ResponseDto saveOrUpdate(@RequestBody @Validated User user){
        ResponseDto rs=new ResponseDto(BizExceptionEnum.SUCCESSFUL_OPERATION);
        SecurityUser securityUser=SecurityUtil.getSecurityUser();
        if(securityUser.getUserType()==BpUserTypeEnum.SHOP_ADMIN.getCode()){
             user.setDrainageId(securityUser.getDrainageId());

        }
        if(user.getId()==null){
            user.setPassword(MD5Util.getMd5Value("123456"));
            user.setUserType(BpUserTypeEnum.SHOP_USER.getCode());
            user.setStatus(1);
        }
        userService.saveOrUpdate(user);
        return rs;
    }


}
